/*
 * Copyright (C) 2010 Sinapsi Spa
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * 
 */
package com.sinapsi.memtracker.sonar;

import static org.apache.commons.lang.builder.ToStringStyle.SHORT_PREFIX_STYLE;

import java.lang.management.MemoryType;
import java.lang.management.MemoryUsage;

import javax.management.openmbean.CompositeData;

import org.apache.commons.lang.builder.ToStringBuilder;

public class Memory {

    String poolName;
    MemoryType type;
    MemoryUsage memoryUsage;

    public Memory(String poolName, MemoryType heap, CompositeData peak) {
        this.poolName = poolName;
        this.type = heap;
        this.memoryUsage = new MemoryUsage(parseLong(peak.get("init")), parseLong(peak.get("used")), parseLong(peak.get("committed")),
                parseLong(peak.get("max")));
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this, SHORT_PREFIX_STYLE).append(type).append(poolName).append(printK(memoryUsage.getMax())).toString();
    }

    protected long parseLong(Object o) {
        try {
            return Long.parseLong(o + "");
        } catch (NumberFormatException e) {
            return 0;
        }
    }
    
    protected String printK(long amount) {
        return (amount >> 10) + "K";
    }

    public String getPoolName() {
        return poolName;
    }

    public MemoryType getType() {
        return type;
    }

    public MemoryUsage getMemoryUsage() {
        return memoryUsage;
    }
}